import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';
import '../../core/constants/app_constants.dart';
import '../../controllers/settings_controller.dart';
import '../layouts/main_layout.dart';
import '../../data/models/app_settings.dart';

/// 设置页面 - 应用配置和用户偏好设置
/// Settings Page - Application configuration and user preferences
class SettingsPage extends StatelessWidget {
  const SettingsPage({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = Get.find<SettingsController>();
    return MainLayout(
      currentIndex: 3, // 设置页面对应索引3
      appBarTitle: '设置',
      child: SingleChildScrollView(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 外观设置 / Appearance settings
            _buildAppearanceSection(controller),
            
            SizedBox(height: 24.h),
            
            // 通知设置 / Notification settings
            _buildNotificationSection(controller),
            
            SizedBox(height: 24.h),
            
            // 数据管理 / Data management
            _buildDataSection(controller),
            
            SizedBox(height: 24.h),
            
            // 隐私设置 / Privacy settings
            _buildPrivacySection(controller),
            
            SizedBox(height: 24.h),
            
            // 关于应用 / About app
            _buildAboutSection(controller),
          ],
        ),
      ),
    );
  }

  /// 构建外观设置区域
  /// Build appearance settings section
  Widget _buildAppearanceSection(SettingsController controller) {
    return _buildSection(
      title: '外观设置',
      icon: Icons.palette,
      children: [
        // 主题模式 / Theme mode
        Obx(() => _buildSettingTile(
          title: '主题模式',
          subtitle: _getThemeModeText(controller.themeMode.toThemeMode()),
          leading: Icon(
            _getThemeModeIcon(controller.themeMode.toThemeMode()),
            color: AppColors.primary,
          ),
          onTap: () => _showThemeModeDialog(controller),
        )),
        
        // 字体大小 / Font size
        Obx(() => _buildSettingTile(
          title: '字体大小',
          subtitle: _getFontSizeText(controller.fontSize.size),
          leading: const Icon(
            Icons.text_fields,
            color: AppColors.primary,
          ),
          onTap: () => _showFontSizeDialog(controller),
        )),
        
        // 语言设置 / Language settings
        Obx(() => _buildSettingTile(
          title: '语言',
          subtitle: controller.language == 'zh' ? '中文' : 'English',
          leading: const Icon(
            Icons.language,
            color: AppColors.primary,
          ),
          onTap: () => _showLanguageDialog(controller),
        )),
      ],
    );
  }

  /// 构建通知设置区域
  /// Build notification settings section
  Widget _buildNotificationSection(SettingsController controller) {
    return _buildSection(
      title: '通知设置',
      icon: Icons.notifications,
      children: [
        // 启用通知 / Enable notifications
        Obx(() => _buildSwitchTile(
          title: '启用通知',
          subtitle: '接收应用通知提醒',
          value: controller.notificationsEnabled,
          onChanged: controller.setNotificationsEnabled,
          icon: Icons.notifications_active,
        )),
        
        // 每日提醒 / Daily reminder
        Obx(() => _buildSwitchTile(
          title: '每日记录提醒',
          subtitle: '提醒您记录今天的情绪',
          value: controller.dailyReminderEnabled,
          onChanged: controller.setDailyReminderEnabled,
          icon: Icons.schedule,
          enabled: controller.notificationsEnabled,
        )),
        
        // 提醒时间 / Reminder time
        Obx(() => controller.dailyReminderEnabled
          ? _buildSettingTile(
              title: '提醒时间',
              subtitle: controller.reminderTime.toString(),
              leading: const Icon(
                Icons.access_time,
                color: AppColors.primary,
              ),
              onTap: () => _showTimePickerDialog(controller),
            )
          : const SizedBox.shrink()),
        
        // 周末提醒 / Weekend reminder
        Obx(() => _buildSwitchTile(
          title: '周末提醒',
          subtitle: '周末也接收记录提醒',
          value: controller.weekendReminderEnabled,
          onChanged: controller.setWeekendReminderEnabled,
          icon: Icons.weekend,
          enabled: controller.dailyReminderEnabled,
        )),
      ],
    );
  }

  /// 构建数据管理区域
  /// Build data management section
  Widget _buildDataSection(SettingsController controller) {
    return _buildSection(
      title: '数据管理',
      icon: Icons.storage,
      children: [
        // 自动备份 / Auto backup
        Obx(() => _buildSwitchTile(
          title: '自动备份',
          subtitle: '定期备份您的数据',
          value: controller.autoBackupEnabled,
          onChanged: controller.setAutoBackupEnabled,
          icon: Icons.backup,
        )),
        
        // 备份频率 / Backup frequency
        Obx(() => controller.autoBackupEnabled
          ? _buildSettingTile(
              title: '备份频率',
              subtitle: controller.backupFrequency.label,
              leading: const Icon(
                Icons.schedule,
                color: AppColors.primary,
              ),
              onTap: () => _showBackupFrequencyDialog(controller),
            )
          : const SizedBox.shrink()),
        
        // 导出数据 / Export data
        _buildSettingTile(
          title: '导出数据',
          subtitle: '将数据导出为文件',
          leading: const Icon(
            Icons.file_download,
            color: AppColors.success,
          ),
          onTap: () => controller.exportData(),
        ),
        
        // 导入数据 / Import data
        _buildSettingTile(
          title: '导入数据',
          subtitle: '从文件导入数据',
          leading: const Icon(
            Icons.file_upload,
            color: AppColors.info,
          ),
          onTap: () => controller.importData(),
        ),
        
        // 清除数据 / Clear data
        _buildSettingTile(
          title: '清除所有数据',
          subtitle: '删除所有记录和设置',
          leading: const Icon(
            Icons.delete_forever,
            color: AppColors.error,
          ),
          onTap: () => _showClearDataDialog(controller),
        ),
      ],
    );
  }

  /// 构建隐私设置区域
  /// Build privacy settings section
  Widget _buildPrivacySection(SettingsController controller) {
    return _buildSection(
      title: '隐私设置',
      icon: Icons.security,
      children: [
        // 应用锁 / App lock
        Obx(() => _buildSwitchTile(
          title: '应用锁',
          subtitle: '使用生物识别或密码保护应用',
          value: controller.appLockEnabled,
          onChanged: controller.setAppLockEnabled,
          icon: Icons.lock,
        )),
        
        // 锁定类型 / Lock type
        Obx(() => controller.appLockEnabled
          ? _buildSettingTile(
              title: '锁定方式',
              subtitle: controller.lockType.label,
              leading: const Icon(
                Icons.fingerprint,
                color: AppColors.primary,
              ),
              onTap: () => _showLockTypeDialog(controller),
            )
          : const SizedBox.shrink()),
        
        // 自动锁定 / Auto lock
        Obx(() => controller.appLockEnabled
          ? _buildSettingTile(
              title: '自动锁定时间',
              subtitle: _getAutoLockTimeText(controller.autoLockTime),
              leading: const Icon(
                Icons.timer,
                color: AppColors.primary,
              ),
              onTap: () => _showAutoLockTimeDialog(controller),
            )
          : const SizedBox.shrink()),
        
        // 数据加密 / Data encryption
        Obx(() => _buildSwitchTile(
          title: '数据加密',
          subtitle: '加密存储敏感数据',
          value: controller.dataEncryptionEnabled,
          onChanged: controller.setDataEncryptionEnabled,
          icon: Icons.enhanced_encryption,
        )),
      ],
    );
  }

  /// 构建关于应用区域
  /// Build about app section
  Widget _buildAboutSection(SettingsController controller) {
    return _buildSection(
      title: '关于应用',
      icon: Icons.info,
      children: [
        // 应用版本 / App version
        _buildSettingTile(
          title: '版本',
          subtitle: AppConstants.appVersion,
          leading: const Icon(
            Icons.info_outline,
            color: AppColors.primary,
          ),
        ),
        
        // 检查更新 / Check updates
        _buildSettingTile(
          title: '检查更新',
          subtitle: '查看是否有新版本',
          leading: const Icon(
            Icons.system_update,
            color: AppColors.primary,
          ),
          onTap: () => controller.checkForUpdates(),
        ),
        
        // 用户协议 / User agreement
        _buildSettingTile(
          title: '用户协议',
          subtitle: '查看用户服务协议',
          leading: const Icon(
            Icons.description,
            color: AppColors.primary,
          ),
          onTap: () => controller.showUserAgreement(),
        ),
        
        // 隐私政策 / Privacy policy
        _buildSettingTile(
          title: '隐私政策',
          subtitle: '查看隐私保护政策',
          leading: const Icon(
            Icons.privacy_tip,
            color: AppColors.primary,
          ),
          onTap: () => controller.showPrivacyPolicy(),
        ),
        
        // 反馈建议 / Feedback
        _buildSettingTile(
          title: '反馈建议',
          subtitle: '向我们提供反馈',
          leading: const Icon(
            Icons.feedback,
            color: AppColors.primary,
          ),
          onTap: () => controller.sendFeedback(),
        ),
        
        // 评分应用 / Rate app
        _buildSettingTile(
          title: '评分应用',
          subtitle: '在应用商店给我们评分',
          leading: const Icon(
            Icons.star_rate,
            color: AppColors.warning,
          ),
          onTap: () => controller.rateApp(),
        ),
        
        // 分析统计 / Analytics
        Obx(() => _buildSwitchTile(
          title: '分析统计',
          subtitle: '帮助改进应用体验',
          value: controller.analyticsEnabled,
          onChanged: controller.setAnalyticsEnabled,
          icon: Icons.analytics,
        )),
        
        // 崩溃报告 / Crash reporting
        Obx(() => _buildSwitchTile(
          title: '崩溃报告',
          subtitle: '自动发送崩溃报告',
          value: controller.crashReportingEnabled,
          onChanged: controller.setCrashReportingEnabled,
          icon: Icons.bug_report,
        )),
      ],
    );
  }

  /// 构建设置区域
  /// Build settings section
  Widget _buildSection({
    required String title,
    required IconData icon,
    required List<Widget> children,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 区域标题 / Section title
          Padding(
            padding: const EdgeInsets.all(AppConstants.paddingMedium),
            child: Row(
              children: [
                Icon(
                  icon,
                  color: AppColors.primary,
                  size: 20,
                ),
                const SizedBox(width: AppConstants.spacingSmall),
                Text(
                  title,
                  style: AppTextStyles.titleMedium.copyWith(
                    color: AppColors.primary,
                  ),
                ),
              ],
            ),
          ),
          
          // 分隔线 / Divider
          Divider(
            height: 1,
            color: AppColors.border,
            indent: AppConstants.paddingMedium,
            endIndent: AppConstants.paddingMedium,
          ),
          
          // 设置项 / Setting items
          ...children,
        ],
      ),
    );
  }

  /// 构建设置项
  /// Build setting tile
  Widget _buildSettingTile({
    required String title,
    String? subtitle,
    Widget? leading,
    Widget? trailing,
    VoidCallback? onTap,
    bool enabled = true,
  }) {
    return ListTile(
      title: Text(
        title,
        style: AppTextStyles.bodyLarge.copyWith(
          color: enabled ? AppColors.textPrimary : AppColors.textSecondary,
        ),
      ),
      subtitle: subtitle != null
          ? Text(
              subtitle,
              style: AppTextStyles.bodyMedium.copyWith(
                color: AppColors.textSecondary,
              ),
            )
          : null,
      leading: leading,
      trailing: trailing ?? (onTap != null ? const Icon(Icons.chevron_right) : null),
      onTap: enabled ? onTap : null,
      enabled: enabled,
    );
  }

  /// 构建开关设置项
  /// Build switch setting tile
  Widget _buildSwitchTile({
    required String title,
    String? subtitle,
    required bool value,
    required ValueChanged<bool> onChanged,
    required IconData icon,
    bool enabled = true,
  }) {
    return _buildSettingTile(
      title: title,
      subtitle: subtitle,
      leading: Icon(
        icon,
        color: enabled ? AppColors.primary : AppColors.textSecondary,
      ),
      trailing: Switch(
        value: value,
        onChanged: enabled ? onChanged : null,
        activeColor: AppColors.primary,
      ),
      enabled: enabled,
    );
  }

  /// 显示主题模式选择对话框
  /// Show theme mode selection dialog
  void _showThemeModeDialog(SettingsController controller) {
    Get.dialog(
      AlertDialog(
        title: const Text('选择主题模式'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildThemeModeOption(controller, ThemeMode.system, '跟随系统'),
            _buildThemeModeOption(controller, ThemeMode.light, '浅色模式'),
            _buildThemeModeOption(controller, ThemeMode.dark, '深色模式'),
          ],
        ),
      ),
    );
  }

  /// 构建主题模式选项
  /// Build theme mode option
  Widget _buildThemeModeOption(
    SettingsController controller,
    ThemeMode mode,
    String label,
  ) {
    return RadioListTile<ThemeMode>(
      title: Text(label),
      value: mode,
      groupValue: controller.themeMode.toThemeMode(),
      onChanged: (value) {
        if (value != null) {
          controller.setThemeMode(AppThemeMode.fromThemeMode(value));
          Get.back();
        }
      },
    );
  }

  /// 显示字体大小选择对话框
  /// Show font size selection dialog
  void _showFontSizeDialog(SettingsController controller) {
    Get.dialog(
      AlertDialog(
        title: const Text('选择字体大小'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildFontSizeOption(controller, 0.8, '小'),
            _buildFontSizeOption(controller, 1.0, '标准'),
            _buildFontSizeOption(controller, 1.2, '大'),
            _buildFontSizeOption(controller, 1.4, '超大'),
          ],
        ),
      ),
    );
  }

  /// 构建字体大小选项
  /// Build font size option
  Widget _buildFontSizeOption(
    SettingsController controller,
    double size,
    String label,
  ) {
    return RadioListTile<double>(
      title: Text(label),
      value: size,
      groupValue: controller.fontSize.size,
      onChanged: (value) {
        if (value != null) {
          // 根据选择的大小值找到对应的FontSize枚举
          FontSize fontSize = FontSize.values.firstWhere(
            (fs) => fs.size == value,
            orElse: () => FontSize.medium,
          );
          controller.setFontSize(fontSize);
          Get.back();
        }
      },
    );
  }

  /// 显示语言选择对话框
  /// Show language selection dialog
  void _showLanguageDialog(SettingsController controller) {
    Get.dialog(
      AlertDialog(
        title: const Text('选择语言'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildLanguageOption(controller, 'zh', '中文'),
            _buildLanguageOption(controller, 'en', 'English'),
          ],
        ),
      ),
    );
  }

  /// 构建语言选项
  /// Build language option
  Widget _buildLanguageOption(
    SettingsController controller,
    String code,
    String label,
  ) {
    return RadioListTile<String>(
      title: Text(label),
      value: code,
      groupValue: controller.language,
      onChanged: (value) {
        if (value != null) {
          controller.setLanguage(value);
          Get.back();
        }
      },
    );
  }

  /// 显示时间选择对话框
  /// Show time picker dialog
  void _showTimePickerDialog(SettingsController controller) async {
    // 解析当前时间字符串为TimeOfDay
    TimeOfDay initialTime = TimeOfDay.now();
    try {
       final timeParts = controller.reminderTime.toString().split(':');
      if (timeParts.length == 2) {
        initialTime = TimeOfDay(
          hour: int.parse(timeParts[0]),
          minute: int.parse(timeParts[1]),
        );
      }
    } catch (e) {
      // 如果解析失败，使用当前时间
    }
    
    final time = await showTimePicker(
      context: Get.context!,
      initialTime: initialTime,
    );
    if (time != null) {
      controller.setReminderTime(time);
    }
  }

  /// 显示备份频率选择对话框
  /// Show backup frequency selection dialog
  void _showBackupFrequencyDialog(SettingsController controller) {
    Get.dialog(
      AlertDialog(
        title: const Text('选择备份频率'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildBackupFrequencyOption(controller, 'daily', '每天'),
            _buildBackupFrequencyOption(controller, 'weekly', '每周'),
            _buildBackupFrequencyOption(controller, 'monthly', '每月'),
          ],
        ),
      ),
    );
  }

  /// 构建备份频率选项
  /// Build backup frequency option
  Widget _buildBackupFrequencyOption(
    SettingsController controller,
    String frequency,
    String label,
  ) {
    return RadioListTile<String>(
      title: Text(label),
      value: frequency,
      groupValue: controller.backupFrequency.value,
      onChanged: (value) {
        if (value != null) {
          controller.setBackupFrequency(BackupFrequency.fromString(value));
          Get.back();
        }
      },
    );
  }

  /// 显示锁定类型选择对话框
  /// Show lock type selection dialog
  void _showLockTypeDialog(SettingsController controller) {
    Get.dialog(
      AlertDialog(
        title: const Text('选择锁定方式'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildLockTypeOption(controller, 'biometric', '生物识别'),
            _buildLockTypeOption(controller, 'password', '密码'),
            _buildLockTypeOption(controller, 'pattern', '图案'),
          ],
        ),
      ),
    );
  }

  /// 构建锁定类型选项
  /// Build lock type option
  Widget _buildLockTypeOption(
    SettingsController controller,
    String type,
    String label,
  ) {
    return RadioListTile<String>(
      title: Text(label),
      value: type,
      groupValue: controller.lockType.value,
      onChanged: (value) {
        if (value != null) {
          controller.setLockType(LockType.fromString(value));
          Get.back();
        }
      },
    );
  }

  /// 显示自动锁定时间选择对话框
  /// Show auto lock time selection dialog
  void _showAutoLockTimeDialog(SettingsController controller) {
    Get.dialog(
      AlertDialog(
        title: const Text('选择自动锁定时间'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildAutoLockTimeOption(controller, 0, '立即'),
            _buildAutoLockTimeOption(controller, 1, '1分钟'),
            _buildAutoLockTimeOption(controller, 5, '5分钟'),
            _buildAutoLockTimeOption(controller, 15, '15分钟'),
            _buildAutoLockTimeOption(controller, 30, '30分钟'),
          ],
        ),
      ),
    );
  }

  /// 构建自动锁定时间选项
  /// Build auto lock time option
  Widget _buildAutoLockTimeOption(
    SettingsController controller,
    int minutes,
    String label,
  ) {
    return RadioListTile<int>(
      title: Text(label),
      value: minutes,
      groupValue: controller.autoLockTime,
      onChanged: (value) {
        if (value != null) {
          controller.setAutoLockTime(value);
          Get.back();
        }
      },
    );
  }

  /// 显示清除数据确认对话框
  /// Show clear data confirmation dialog
  void _showClearDataDialog(SettingsController controller) {
    Get.dialog(
      AlertDialog(
        title: const Text('清除所有数据'),
        content: const Text('此操作将删除所有记录和设置，且无法恢复。确定要继续吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.clearAllData();
            },
            style: TextButton.styleFrom(
              foregroundColor: AppColors.error,
            ),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 获取主题模式文本
  /// Get theme mode text
  String _getThemeModeText(ThemeMode mode) {
    switch (mode) {
      case ThemeMode.system:
        return '跟随系统';
      case ThemeMode.light:
        return '浅色模式';
      case ThemeMode.dark:
        return '深色模式';
    }
  }

  /// 获取主题模式图标
  /// Get theme mode icon
  IconData _getThemeModeIcon(ThemeMode mode) {
    switch (mode) {
      case ThemeMode.system:
        return Icons.brightness_auto;
      case ThemeMode.light:
        return Icons.brightness_high;
      case ThemeMode.dark:
        return Icons.brightness_low;
    }
  }

  /// 获取字体大小文本
  /// Get font size text
  String _getFontSizeText(double size) {
    if (size <= 0.8) return '小';
    if (size <= 1.0) return '标准';
    if (size <= 1.2) return '大';
    return '超大';
  }



  /// 获取自动锁定时间文本
  /// Get auto lock time text
  String _getAutoLockTimeText(int minutes) {
    if (minutes == 0) return '立即';
    return '${minutes}分钟';
  }
}